package com.mayblackcat.dy.service.impl;

import com.mayblackcat.dy.FrontEndData.AjaxResult;
import com.mayblackcat.dy.constant.Constants;
import com.mayblackcat.dy.dao.LoginDao;
import com.mayblackcat.dy.entity.User;
import com.mayblackcat.dy.exception.NotFoundException;
import com.mayblackcat.dy.service.LoginService;
import com.mayblackcat.dy.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginDao loginDao;
    private static final int notStatus=0;

    //查找
    @Override
    public User findByUser(String username, String password) {
        return loginDao.findByUser(username, MD5Util.inputPassToDBPass(password));
    }

    @Transactional
    public synchronized boolean updateStatus(User user){
        int currentStatus=loginDao.getStatusById(user.getId());
        if(currentStatus!=0){
            currentStatus=0;
            user.setStatus(currentStatus);
            loginDao.updateStatus(user);
            return true;
        }
        return false;
    }

    //注册
    @Override
    @Transactional
    public AjaxResult registerUser(String username, String password,String email,String sex) {
        AjaxResult ajaxResult=null;
        if (username==""||password==""||username.length()<5||password.length()<5||username.length()>20||password.length()>20){

            return ajaxResult=new AjaxResult(AjaxResult.Type.ERROR,"fail",null);
        }else if(loginDao.findByName(username)!=null){

            return ajaxResult=new AjaxResult(AjaxResult.Type.ERROR,"fail",null);
        }else {
            //注册成功
            loginDao.registerUser(username, MD5Util.inputPassToDBPass(password),email,sex,new String("https://tse4-mm.cn.bing.net/th/id/OIP-C.UJn6UIedh0fIZk5V4f_5zgHaE8?pid=ImgDet&rs=1"),new Date(),notStatus);

            return ajaxResult=new AjaxResult(AjaxResult.Type.SUCCESS,"success");
        }
    }

    @Override
    public List<User> findByAll() {
        return loginDao.findByAll();
    }
}
